import React, {useEffect, useCallback, useRef, useState, useLayoutEffect} from 'react';
import {
    FlatList,
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
    SafeAreaView,
} from 'react-native';
import {LoadingView, Toast} from "react-native-gzdsx-elements";
import {defaultNavigationConfigure} from "../../base/navconfig";
import OrderActionBar from "./OrderActionBar";
import {ListItem} from 'react-native-elements';
import ImageIcon from "../../components/ImageIcon";
import FastImage from "react-native-fast-image";
import OrderTabs from "./OrderTabs";
import {useNavigation, useRoute} from "@react-navigation/native";
import StatusBarCtl from "../../utils/StatusBarCtl";
import ApiService from "../../utils/ApiService";
import Empty from "../../components/Empty";
import OrderService from "./OrderService";

const OrderTabView = ({onChange = () => null, activeIndex = 0}) => {
    const [tabIndex, setTabIndex] = useState(0);

    useEffect(() => {
        setTabIndex(activeIndex);
    }, [activeIndex]);

    return (
        <View style={styles.tabContainer}>
            {
                OrderTabs.map((tab, index) => (
                    <TouchableOpacity
                        key={index.toString()}
                        style={styles.tabItem}
                        activeOpacity={1}
                        onPress={() => {
                            setTabIndex(index);
                            onChange && onChange(tab);
                        }}
                    >
                        <Text style={[styles.tabText, tabIndex === index && styles.tabActive]}>{tab.name}</Text>
                    </TouchableOpacity>
                ))
            }
        </View>
    );
}

const OrderListItem = (props) => {
    const navigation = useNavigation();
    const [reasons, setReasons] = useState([]);
    const {order = {}} = props;
    return (
        <View style={styles.order}>
            <ListItem containerStyle={styles.shopContainer}>
                <ListItem.Content style={{flexDirection: 'row', justifyContent: 'flex-start'}}>
                    <ImageIcon
                        source={require('../../images/icon/shop.png')}
                        size={20} color={"#555"}
                        style={{marginRight: 3}}
                    />
                    <ListItem.Title style={styles.shopName}>{order.shop_name}</ListItem.Title>
                </ListItem.Content>
                <ListItem.Subtitle style={styles.orderState}>{order.status_des}</ListItem.Subtitle>
            </ListItem>
            <View>
                {
                    order.items.map((item, idx) => (
                        <ListItem
                            activeOpacity={1}
                            key={idx.toString()}
                            containerStyle={styles.orderItem}
                            onPress={() => {
                                navigation.navigate('OrderDetail', {order_id: order.order_id});
                            }}
                        >
                            <FastImage source={{uri: item.image}} style={css.itemImage}/>
                            <View style={css.itemContent}>
                                <Text numberOfLines={2} style={css.itemTitle}>{item.title}</Text>
                                {
                                    item.sku_title ?
                                        <View style={{flexDirection: 'row', marginTop: 5}}>
                                            <TouchableOpacity style={styles.skuTouch}>
                                                <Text style={styles.skuTitle}>{item.sku_title}</Text>
                                            </TouchableOpacity>
                                        </View>
                                        : null
                                }
                                <View style={{flex: 1}}/>
                            </View>
                            <View style={css.itemData}>
                                <Text style={css.itemPrice}>￥{item.price}</Text>
                                <Text style={css.itemQuantity}>x{item.quantity}</Text>
                                <View style={{flex: 1}}/>
                            </View>
                        </ListItem>
                    ))
                }
            </View>
            <View style={css.simpleTotal}>
                <Text style={css.simpleTotalText}>
                    共计{order.product_num}件商品 合计:{order.total_fee}(含运费￥{order.shipping_fee})
                </Text>
            </View>
            <OrderActionBar {...props}/>
        </View>
    );
}

const OrderListView = ({options = {}}) => {
    const navigation = useNavigation();

    const [dataList, setDataList] = useState([]);
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);

    const offset = useRef(0);
    const requesting = useRef(false);

    const fetchData = () => {
        ApiService.get('/trade/boughts', {
            params: {
                ...options,
                offset: offset.current,
                limit: 15
            }
        }).then(response => {
            let {items} = response.result;
            if (loadingMore) {
                setDataList(dataList.concat(items));
            } else {
                setDataList(items);
            }
        }).catch(reason => {
            console.log(reason.message);
        }).finally(() => {
            requesting.current = false;
            setLoading(false);
            setRefreshing(false);
            setLoadingMore(false);
        })
    }

    useEffect(() => {
        setDataList([]);
        fetchData();
    }, [options])

    useEffect(() => {
        if (refreshing) {
            offset.current = 0;
            fetchData();
        }
    }, [refreshing]);

    useEffect(() => {
        if (loadingMore) {
            offset.current += 15;
            fetchData();
        }
    }, [loadingMore]);

    const onRefresh = () => {
        if (requesting.current) {
            return false;
        }

        setRefreshing(true);
    }

    const onEndReached = () => {
        if (requesting.current) {
            return false;
        }

        if (dataList.length === total) {
            return false;
        }

        setLoadingMore(true);
    }

    if (loading) {
        return <LoadingView/>;
    }

    return (
        <FlatList
            data={dataList}
            renderItem={({item, index}) => (
                <OrderListItem
                    order={item}
                    onPay={() => {
                        OrderService.pay(item.order_id).then(()=>{

                        }).catch(reason => {

                        });
                    }}
                />
            )}
            keyExtractor={(item, index) => index.toString()}
            ItemSeparatorComponent={() => <View style={{height: 10}}/>}
            refreshing={refreshing}
            onRefresh={onRefresh}
            onEndReached={onEndReached}
            onEndReachedThreshold={0.2}
            ListEmptyComponent={
                <Empty description={'暂无此类订单'} style={{height: 300}}/>
            }
            ListFooterComponent={
                <LoadingView
                    text="正在加载更多"
                    show={loadingMore}
                    style={{paddingTop: 10, paddingBottom: 10}}/>}
            style={{flex: 1}}
        />
    )
}

const OrderList = () => {
    const navigation = useNavigation();
    const [tab, setTab] = useState('');

    useLayoutEffect(() => {
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            headerTitle: '我的订单'
        });

        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, [navigation])

    return (
        <SafeAreaView style={{flex: 1}}>
            <OrderTabView
                activeIndex={0}
                onChange={tb => {
                    setTab(tb.value);
                }}
            />
            <OrderListView options={{tab}}/>
        </SafeAreaView>
    )
}

export default OrderList;

const styles = StyleSheet.create({
    tabContainer: {
        flexDirection: 'row',
        backgroundColor: '#fff',
        borderBottomWidth: 0.5,
        borderBottomColor: '#e5e5e5'
    },
    tabItem: {
        flex: 1,
        flexDirection: 'column',
        alignItems: 'center',
        paddingVertical: 15
    },
    tabText: {
        textAlign: 'center',
        fontSize: 16
    },
    tabActive: {
        fontWeight: '800',
        color: '#f00',
    },
    order: {
        backgroundColor: '#fff'
    },
    orderNo: {
        fontSize: 14,
        color: '#333',
        lineHeight: 16,
        marginLeft: 5,
        marginRight: 10,
        flex: 1
    },
    orderState: {
        fontSize: 14,
        color: '#FC461E',
        lineHeight: 16,
    },
    shopContainer: {
        paddingHorizontal: 10,
        borderBottomColor: '#f2f2f2',
        borderBottomWidth: 0.5
    },
    shopName: {
        fontSize: 16,
        color: '#333'
    },
    orderItem: {
        padding: 10,
        flexDirection: 'row',
    },
    itemImage: {
        width: 80,
        height: 80,
        marginRight: 15
    },
    itemContent: {
        flex: 1
    },
    itemTitle: {
        fontSize: 14,
        fontWeight: '400',
        color: '#333'
    },
    itemData: {
        marginLeft: 30
    },
    itemPrice: {
        paddingTop: 2,
        fontSize: 14,
        color: '#333',
        textAlign: 'right'
    },
    itemQuantity: {
        paddingTop: 5,
        fontSize: 14,
        color: '#777',
        textAlign: 'right'
    },
    simpleTotal: {
        padding: 10,
        borderBottomColor: '#e5e5e5',
        borderBottomWidth: 0.5,
    },
    simpleTotalText: {
        flex: 1,
        textAlign: 'right',
        fontSize: 12,
        color: '#333'
    },
    skuTouch: {
        backgroundColor: '#f2f2f2',
        paddingHorizontal: 5,
        paddingVertical: 3,
        borderRadius: 5
    },
    skuTitle: {
        fontSize: 12, color: '#555'
    }
});

const css = {

    item: {
        padding: 10,
        flexDirection: 'row',
    },
    itemImage: {
        width: 80,
        height: 80,
        borderRadius: 5,
        resizeMode: 'cover'
    },
    itemContent: {
        flex: 1,
        alignItems: 'flex-start',
        justifyContent: 'flex-start'
    },
    itemTitle: {
        fontSize: 14,
        fontWeight: '400',
        color: '#333'
    },
    itemData: {
        marginLeft: 30
    },
    itemPrice: {
        paddingTop: 2,
        fontSize: 14,
        color: '#333',
        textAlign: 'right'
    },
    itemQuantity: {
        paddingTop: 5,
        fontSize: 14,
        color: '#777',
        textAlign: 'right'
    },
    simpleTotal: {
        padding: 10,
        borderBottomColor: '#e5e5e5',
        borderBottomWidth: 0.5,
    },
    simpleTotalText: {
        flex: 1,
        textAlign: 'right',
        fontSize: 12,
        color: '#333'
    },
};
